package com.ruoyi.web.controller.system;

import com.ruoyi.WebSocketTemplate;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.text.NumberFormat;
import java.util.*;

/**
 * 植保 信息操作处理
 *
 * @author ruoyi
 * @date 2019-08-29
 */
@Controller
@RequestMapping("/system/ncZhibao")
public class
NcZhibaoController extends BaseController {
    private String prefix = "system/ncZhibao";

    @Autowired
    private INcZhibaoService ncZhibaoService;
    @Autowired
    private INcZhibaoDrugsService ncZhibaoDrugsService;
    @Autowired
    private INcYaoClassService yaoClassService;
    @Autowired
    private INcPlanService planService;
    @Autowired
    private INcXiaoduLogsService xiaoduLogsService;

    @Autowired
    private INcStageMirrorService stageService;
    @Autowired
    private INcCaiService ncCaiService;
    @Autowired
    private ISysDictDataService dataService;
    @Autowired
    private INcMeterialService meterialService;
    @Autowired
    private ISysDictDataService sysDictDataService;
    @Autowired
    private INcZhibaoDrugsService drugsService;
    @Autowired
    private ISysNoticeService noticeService;
    @Autowired
    private WebSocketTemplate socketTemplate;

    @Autowired
    private ISysUserService userService;

    @RequiresPermissions("system:ncZhibao:view")
    @GetMapping()
    public String ncZhibao() {
        return prefix + "/ncZhibao";
    }

    /**
     * 查询植保列表
     */
    @RequiresPermissions("system:ncZhibao:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(NcZhibao ncZhibao, Integer conformStatus) {
        startPage();
        ncZhibao.setConformStatus(conformStatus);
        List<NcZhibao> list = ncZhibaoService.selectNcZhibaoList(ncZhibao);
        return getDataTable(list);
    }


    /**
     * 导出植保列表
     */
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(NcZhibao ncZhibao) {
        List<NcZhibao> list = ncZhibaoService.selectNcZhibaoJiluList(ncZhibao);
        ExcelUtil<NcZhibao> util = new ExcelUtil<NcZhibao>(NcZhibao.class);
        return util.exportExcel(list, "植保订单详情");
    }

    /**
     * 新增植保
     */
    @GetMapping("/add")
    public String add(ModelMap map, NcZhibao zhibao) {
        List<SysDictData> syslist = sysDictDataService.selectDictDataByType("unitType");
        map.put("unitType", syslist);
        map.put("user", ShiroUtils.getSysUser().getLoginName());
        return prefix + "/add";
    }

    @GetMapping("/edit/{zhibaoId}")
    public String edit(@PathVariable("zhibaoId") Long zhibaoId, ModelMap mmap) {
        NcZhibao ncZhibao = ncZhibaoService.selectNcZhibaoById(zhibaoId);
        mmap.put("ncZhibao", ncZhibao);
        mmap.put("zhibaoId", zhibaoId);
        List<SysDictData> syslist = sysDictDataService.selectDictDataByType("unitType");
        mmap.put("unitType", syslist);
        mmap.put("user", ShiroUtils.getSysUser().getLoginName());
        return prefix + "/edit";
    }

    /**
     * 修改保存植保
     */
    @RequiresPermissions("system:ncZhibao:edit")
    @Log(title = "植保", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(NcZhibao ncZhibao) {
        Long zhibaoId = ncZhibao.getZhibaoId();
        //修改植保表
        NcZhibao nc = new NcZhibao();
        nc.setZhibaoId(zhibaoId);
        nc.setCauses(ncZhibao.getCauses());//发病原因
        nc.setProposal(ncZhibao.getProposal());//植保意见
        nc.setRemark(ncZhibao.getRemark());
        ncZhibaoService.updateNcZhibao(nc);
        //清空之前的
        NcZhibaoDrugs drugs = new NcZhibaoDrugs();
        drugs.setZhibaoId(zhibaoId);
        List<NcZhibaoDrugs> drugList = drugsService.selectNcZhibaoDrugsList(drugs);
        for (NcZhibaoDrugs i : drugList) {
            drugsService.deleteNcZhibaoDrugsByIds(i.getZhibaoDrugsId() + ",");
        }
        if (ncZhibao.getYaos() != null) {
            for (int i = 0; i < ncZhibao.getYaos().size(); i++) {
                Map map = ncZhibao.getYaos().get(i);
                NcZhibaoDrugs eterial = new NcZhibaoDrugs();
                eterial.setZhibaoId(zhibaoId);
                eterial.setDrugCode((String) map.get("pici"));
                eterial.setUnit((String) map.get("unit"));
                eterial.setDrugAmount(Integer.valueOf(String.valueOf(map.get("yaoCount"))));
                eterial.setYaoId((String) map.get("yaoId"));
                eterial.setDrugName((String) map.get("yaoName"));
                eterial.setExecuteType(ncZhibao.getExecuteType());
                drugsService.insertNcZhibaoDrugs(eterial);
            }
        }
        return AjaxResult.success(1);

    }

    /**
     * 删除植保
     */
    @RequiresPermissions("system:ncZhibao:remove")
    @Log(title = "植保", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(ncZhibaoService.deleteNcZhibaoByIds(ids));
    }

    /**
     * 植保列表中的确认
     */
    @GetMapping("/enterYao/{id}")
    public String edit2(@PathVariable("id") Long zhibaoId, Map<String, Object> map) {
        NcZhibao ncZhibao = ncZhibaoService.selectNcZhibaoById(zhibaoId);
        map.put("ncZhibao", ncZhibao);
        map.put("zhibaoId", zhibaoId);
        List<SysDictData> syslist = sysDictDataService.selectDictDataByType("unitType");
        map.put("unitType", syslist);
        map.put("user", ShiroUtils.getSysUser().getLoginName());
        return prefix + "/edit2";
    }

    /*
     * 录入药品信息
     */
    @RequiresPermissions("system:ncZhibao:addyao")
    @Log(title = "植保", businessType = BusinessType.INSERT)
    @PostMapping("/addyao")
    @ResponseBody
    public AjaxResult addQueren(NcZhibao ncZhibao) {

        //修改植保表
        NcZhibao nc = new NcZhibao();
        nc.setConformStatus(1);
        nc.setZhibaoId(ncZhibao.getZhibaoId());
        nc.setCauses(ncZhibao.getCauses());//发病原因
        nc.setProposal(ncZhibao.getProposal());//植保意见
        nc.setRemark(ncZhibao.getRemark());
        ncZhibaoService.updateNcZhibao(nc);
        if (ncZhibao.getYaos() != null) {
            for (int i = 0; i < ncZhibao.getYaos().size(); i++) {
                Map map = ncZhibao.getYaos().get(i);
                NcZhibaoDrugs eterial = new NcZhibaoDrugs();
                eterial.setZhibaoId(ncZhibao.getZhibaoId());
                eterial.setDrugCode((String) map.get("pici"));
                eterial.setUnit((String) map.get("unit"));
                eterial.setDrugAmount(Integer.valueOf(String.valueOf(map.get("yaoCount"))));
                eterial.setYaoId((String) map.get("yaoId"));
                eterial.setDrugName((String) map.get("yaoName"));
                eterial.setCreateBy(ncZhibao.getCreateBy());
                eterial.setExecuteType(ncZhibao.getExecuteType());
                eterial.setCreateTime(ncZhibao.getCreateTime());
                drugsService.insertNcZhibaoDrugs(eterial);
            }

        }
        return AjaxResult.success("添加植保用药成功");

    }

    /**
     * 查询植保记录列表
     */
    @RequiresPermissions("system:ncZhibao:getjilulist")
    @PostMapping("/getjilulist")
    @ResponseBody
    public TableDataInfo getZhiList(NcZhibao ncZhibao, String beginTime, String endTime, Integer conformStatus) {
        startPage();
        ncZhibao.setConformStatus(conformStatus);
        List<NcZhibao> list = ncZhibaoService.selectNcZhibaoJiluList(ncZhibao);
        return getDataTable(list);
    }

    /**
     * 确认生成检测单
     */
    @Log(title = "确认生成检测单", businessType = BusinessType.OTHER)
    @PostMapping("/confirmTable")
    @ResponseBody
    public AjaxResult confirmTable(String ids) {
        SysUser user = ShiroUtils.getSysUser();
        //TODO 生成植保计划单
        return toAjax(ncZhibaoService.createOrderByIds(ids, user));
    }

    //修改保存植保记录    }
    @RequiresPermissions("system:ncZhibao:editSaveZhibaoJilu")
    @Log(title = "植保", businessType = BusinessType.UPDATE)
    @PostMapping("/editSaveZhibaoJilu")
    @ResponseBody
    public AjaxResult editSaveZhibaoJilu(NcZhibao ncZhibao) {
        Long zhibaoId = ncZhibao.getZhibaoId();
        return toAjax(ncZhibaoService.updateZhibaoLog(ncZhibao));
    }

    //添加保存植保记录
    @RequiresPermissions("system:ncZhibao:addSaveZhibaoJilu")
    @Log(title = "植保", businessType = BusinessType.INSERT)
    @PostMapping("/addSaveZhibaoJilu")
    @Transactional
    @ResponseBody
    public AjaxResult addSaveZhibaoJilu(NcZhibao ncZhibao) {
        NcZhibao zhi = new NcZhibao();
        zhi.setCauses(ncZhibao.getCauses());//发病原因
        zhi.setProposal(ncZhibao.getProposal());//植保意见
        zhi.setSymptom(ncZhibao.getSymptom());
        zhi.setConformStatus(ncZhibao.getConformStatus());
        zhi.setPlanId(Long.valueOf(ncZhibao.getPlanId()));
        zhi.setSourceType(2);
        zhi.setCreateBy(ShiroUtils.getSysUser().getLoginName());
        zhi.setCreateTime(new Date());
        zhi.setRemark(ncZhibao.getRemark());
        ncZhibaoService.insertNcZhibao(zhi);
        if (ncZhibao.getYaos() != null) {
            for (int i = 0; i < ncZhibao.getYaos().size(); i++) {
                Map map = ncZhibao.getYaos().get(i);
                NcZhibaoDrugs eterial = new NcZhibaoDrugs();
                eterial.setZhibaoId(zhi.getZhibaoId());
                eterial.setDrugCode((String) map.get("pici"));
                eterial.setUnit((String) map.get("unit"));
                eterial.setDrugAmount(Integer.valueOf(String.valueOf(map.get("yaoCount"))));
                eterial.setYaoId((String) map.get("yaoId"));
                eterial.setDrugName((String) map.get("yaoName"));
                eterial.setCreateBy(ShiroUtils.getSysUser().getLoginName());
                eterial.setCreateTime(new Date());
                eterial.setExecuteType(ncZhibao.getExecuteType());
                eterial.setCreateTime(ncZhibao.getCreateTime());
                drugsService.insertNcZhibaoDrugs(eterial);
            }
        }
        return AjaxResult.success("添加植保记录成功!");

    }

    /**
     * 选择药品树
     */
    @GetMapping("/selectYaoTree/{treeId}")
    public String selectYaoClassTree(@PathVariable("treeId") Long yaoClassId, ModelMap mmap) {
        mmap.put("yao", yaoClassService.selectYaoClassById(yaoClassId));
        return prefix + "/tree";
    }

    /**
     * 加载药品列表树
     */
    @GetMapping("/treeData")
    @ResponseBody
    public List<Ztree> treeData() {
        List<Ztree> ztrees = yaoClassService.selectYaoClassTree(new NcYaoClass());
        return ztrees;
    }

    /*植保请求记录*/
    @GetMapping("/ncZhibaoLogs")
    public String ncZhibaoLogs(NcPlan plan, ModelMap mmap) {
        mmap.put("plan", plan);
        return prefix + "/ncZhibao-logs";
    }

    /*植保请求*/
    @GetMapping("/addRequest")
    public String addRequest(Long planId, Long stageId, ModelMap mmap) {
        NcPlan plan = planService.selectNcPlanById(planId);
        NcStageMirror stage = stageService.selectNcStageMirrorById(stageId);
        mmap.put("planId", planId);
        mmap.put("stageId", stageId);
        return prefix + "/add-request";
    }


    /*植保请求*/
    @PostMapping("/addRequestSave")
    @ResponseBody
    public AjaxResult addRequestSave(NcZhibao zhibao, ModelMap mmap) {
        NcPlan plan = planService.selectNcPlanById(zhibao.getPlanId());
        zhibao.setTeam(plan.getTeam());
        zhibao.setTeamCn(plan.getTeamCn());
        zhibao.setCreateBy(ShiroUtils.getLoginName());
        zhibao.setCreateTime(new Date());
        zhibao.setConformStatus(2);//待确认
        zhibao.setSourceType(1);//推送


        SysNotice notice = null;
        SysUser user = new SysUser();
        List<SysUser> users = new ArrayList<>();

        NcPlan ncPlan = planService.selectNcPlanById(zhibao.getPlanId());

        notice = new SysNotice();

        notice.setNoticeTitle("植保请求");
        notice.setNoticeContent("计划编号【"+plan.getPlanCode() + "】 " + plan.getCropNameCn()+ " " + plan.getCropTypeCn()+ " " + plan.getCropVarietiesCn());
        notice.setNoticeType("3");
        notice.setStatus("0");
        notice.setDeptId("2"); //设置选择用户
        notice.setReadType(2); //设置未读
        notice.setCreateTime(new Date());
        notice.setCreateBy(ShiroUtils.getLoginName());

        //植保部门
        user.setDeptId(Long.parseLong("208"));
        List<SysUser> sysUsers1 = userService.selectUserList(user);
        users.addAll(sysUsers1);

        String userId = "";
        if (!users.isEmpty()) {
            for (SysUser sysUser : users) {
                userId += sysUser.getUserId() + ",";
            }
        }
        notice.setUserId(userId);
        int no = noticeService.insertNotice(notice);
        if (no > 0) {
            socketTemplate.sendMessage(notice);
        }


        return AjaxResult.success(ncZhibaoService.insertNcZhibao(zhibao));
    }

    //前端页面中的植保管理：植保管理
    @GetMapping("/planZhibao")
    public String planProtection(NcZhibao ncZhibao, String beginTime, String endTime, ModelMap map) {
        //时间的处理
        if (StringUtils.isNotEmpty(beginTime)) {
            ncZhibao.getParams().put("beginTime", beginTime);
        }
        if (StringUtils.isNotEmpty(endTime)) {
            ncZhibao.getParams().put("endTime", endTime);
        }
        map.put("beginTime", beginTime);
        map.put("endTime", endTime);
        //统计蔬菜各分类的次数
        NcCai cai = new NcCai();
        cai.setAncestors("0");
        cai.setParentId(new Long(0));
        List<NcCai> result = ncCaiService.selectBigClass(cai);
        List<Long> longs = new ArrayList<>();
        List<String> caiName = new ArrayList<String>();
        for (int i = 0; i < result.size(); i++) {
            caiName.add(result.get(i).getCaiName());
            ncZhibao.getParams().put("ancestors", result.get(i).getCaiId());
            Long count = ncZhibaoService.selectChartAmount(ncZhibao);
            longs.add(count);
        }
        //所有大类的名称
        map.put("caiName", caiName);
        //所有大类的植保次数列表
        map.put("longs", longs);
        int number = 0;
        for (int i = 0; i < longs.size(); i++) {
            number += longs.get(i);
        }
        map.put("number", number);
        NumberFormat numberFormat = NumberFormat.getInstance();  // 设置精确到小数点后2位
        numberFormat.setMaximumFractionDigits(2);
        //统计所有的占比
        List<String> ratio = new ArrayList<String>();
        for (int i = 0; i < longs.size(); i++) {
            if (number != 0) {
                ratio.add(numberFormat.format(longs.get(i) / number * 100));
            } else {
                ratio.add("0.00");
            }

        }
        //将所有菜名、次数、占比封装成一个list
        List<NcCai> ncCaiList = new ArrayList<NcCai>();
        for (int i = 0; i < result.size(); i++) {
            NcCai nc = new NcCai();
            nc.setCaiName(caiName.get(i));
            nc.setCaiId(result.get(i).getCaiId());
            Map hashMap = new HashMap();
            hashMap.put("longs", longs.get(i));
            hashMap.put("ratio", ratio.get(i));
            nc.setPlanCounts(hashMap);
            ncCaiList.add(nc);
        }
        map.put("ncCai", ncCaiList);

        return prefix + "/plantProtection";
    }

    //前端页面中的植保管理：消毒管理
    @GetMapping("/zhibaoXiaodu")
    public String zhibaoXiaodu(NcXiaoduLogs ncXiaoduLogs, String beginTime, String endTime, ModelMap map) {
        //时间的处理
        if (StringUtils.isNotEmpty(beginTime)) {
            ncXiaoduLogs.getParams().put("beginTime", beginTime);
        }
        if (StringUtils.isNotEmpty(endTime)) {
            ncXiaoduLogs.getParams().put("endTime", endTime);
        }
        map.put("beginTime", beginTime);
        map.put("endTime", endTime);

        NumberFormat numberFormat = NumberFormat.getInstance();  // 设置精确到小数点后2位
        numberFormat.setMaximumFractionDigits(2);
        int number = 0;
        if (xiaoduLogsService.selectNcXiaoduLogsAmount(ncXiaoduLogs) != null) {
            number = xiaoduLogsService.selectNcXiaoduLogsAmount(ncXiaoduLogs).getAmount();
            //总的消毒次数
            map.put("xiaoduAmount", number);
        } else {
            map.put("xiaoduAmount", 0);
        }
        List<SysDictData> selectDictDataByType = dataService.selectDictDataByType("xiaoduType");
        List<NcCai> xiaoduList = new ArrayList<NcCai>();
        //消毒次数
        List<Integer> xiaoduCount = new ArrayList<>();
        List<String> xiaoduType = new ArrayList<>();
        for (int i = 0; i < selectDictDataByType.size(); i++) {
            xiaoduType.add(selectDictDataByType.get(i).getDictLabel());
            NcCai cai = new NcCai();
            Map hashMap = new HashMap();
            ncXiaoduLogs.setXdType(Long.valueOf(selectDictDataByType.get(i).getDictValue()));
            if (xiaoduLogsService.selectNcXiaoduLogsAmount(ncXiaoduLogs) != null) {
                int num = xiaoduLogsService.selectNcXiaoduLogsAmount(ncXiaoduLogs).getAmount();
                xiaoduCount.add(num);
                hashMap.put("amount", num);
                if (number != 0) {
                    hashMap.put("ratio", numberFormat.format((float) num / (float) number * 100));
                } else {
                    hashMap.put("ratio", "0.00");
                }

            } else {
                xiaoduCount.add(0);
                hashMap.put("amount", 0);
                hashMap.put("ratio", 0);
            }
            cai.setPlanCounts(hashMap);
            cai.setCaiName(selectDictDataByType.get(i).getDictLabel());
            cai.setCaiId(Long.valueOf(selectDictDataByType.get(i).getDictValue()));
            xiaoduList.add(cai);
        }
        map.put("xiaoduList", xiaoduList);
        map.put("xiaoduCount", xiaoduCount);
        map.put("xiaoduType", xiaoduType);

        return prefix + "/ncZhibaoXiaodu";
    }

    /*前端植保管理详情请求*/
    @GetMapping("/detail")
    @RequiresPermissions("system:ncZhibao:view")
    public String ncZhibaoDetail(NcZhibao ncZhibao, ModelMap mmap, String beginTime, String endTime, String caiId) {
        mmap.put("beginTime", beginTime);
        mmap.put("endTime", endTime);
        mmap.put("caiId", caiId);
        return prefix + "/ncZhibaoDetail";
    }

    //前端植保查询
    @GetMapping("/selectDetail")
    @RequiresPermissions("system:ncZhibao:view")
    public String selectDetail(ModelMap mmap, @RequestParam(name = "benginTime") String beginTime, @RequestParam(name = "endTime") String endTime, @RequestParam(name = "caiId") String caiId) {
        mmap.put("beginTime", beginTime);
        mmap.put("endTime", endTime);
        mmap.put("caiId", caiId);
        return prefix + "/ncZhibaoDetail";
    }

    /**
     * 查询植保记录列表
     */
    @RequiresPermissions("system:ncZhibao:getjilulist")
    @PostMapping("/selectzhibaoDetailList")
    @ResponseBody
    public TableDataInfo selectzhibaoDetail(NcZhibao ncZhibao, String beginTime, String endTime, Integer conformStatus, String caiId) {
        startPage();
        ncZhibao.setConformStatus(conformStatus);
        ncZhibao.getParams().put("ancestors", caiId);
        ncZhibao.getParams().put("beginTime", beginTime);
        ncZhibao.getParams().put("endTime", endTime);

        List<NcZhibao> list = ncZhibaoService.selectzhibaoDetail(ncZhibao);
        return getDataTable(list);
    }

    /**
     * @param dataSpan 时间跨度 1:年 2：月 3：日
     * @return
     */
    @PostMapping("/zhibaoQuery")
    @ResponseBody
    public TableDataInfo chickenQuery(Integer dataSpan, String beginTime, String endTime, Integer zhibaoType) {
        //使用zhibaoType保存各分类caiId

        List<Map> list = ncZhibaoService.selectCountByTime(dataSpan, beginTime, endTime, zhibaoType);
        return getDataTable(list);
    }

    //加载物资树
    @GetMapping("/selectMeterialTree/{parentId}")
    public String selectMeterialTree(@PathVariable("parentId") Long parentId, ModelMap mmap) {
        mmap.put("meterial", meterialService.selectMeterialById(parentId));
        return prefix + "/wuziTree";
    }

    /**
     * 加载物资列表树
     */
    @GetMapping("/wuzitreeData")
    @ResponseBody
    public List<Ztree> wuziTreeDate() {
        NcMeterial wuzi = new NcMeterial();
        wuzi.setAncestors("0,100,141");
        List<Ztree> ztrees = meterialService.selectMeterialTree(wuzi);
        return ztrees;
    }

    /**
     * 根据植保信息
     */
    @PostMapping("/zhibaoList")
    @ResponseBody
    public TableDataInfo daPengList(NcZhibao zhibao) {
        NcZhibao zhi = new NcZhibao();
        zhi.setZhibaoId(zhibao.getZhibaoId());
        List<NcZhibao> infos = ncZhibaoService.selectNcZhibaoList(zhi);
        return getDataTable(infos);
    }

    /**
     * 根据作物品种id查找正在执行的计划
     */
    @PostMapping("/zhibaoPlanList")
    @ResponseBody
    public TableDataInfo planList(Long treeId, Integer type) {
        if (type == null) {
            type = 0;
        }
        //查询节点为
        NcCai cai = ncCaiService.selectCaiById(treeId);
        if (cai != null && cai.getAncestors() != null) {
            if (cai.getAncestors().split(",").length == 3) {
                NcPlan plan = new NcPlan();
                plan.setCropVarieties(treeId);
                plan.setStatus("3");
                if (type > 0)
                    plan.setPlanType(type);
                List<NcPlan> planList = planService.selectNcPlanList(plan);
                return getDataTable(planList);
            }
        }
        return getDataTable(new ArrayList<>());
    }
}
